package com.mutouren.web;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ExceptionHandler;

import com.mutouren.common.entity.Result;
import com.mutouren.common.entity.ResultCode;
import com.mutouren.common.exception.ExceptionUtils;
import com.mutouren.common.log.LogAlias;
import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;
import com.mutouren.common.utils.JsonUtils;

public class BaseApi {

	private static Logger errorLogger = LogManager.getLogger(LogAlias.SystemError.name());

	@ExceptionHandler(Throwable.class)
	public void doError(Throwable t, HttpServletResponse response) {
		Result result = new Result();
		result.setCode(ResultCode.EXCEPTION.value);
		result.setMessage(t.getMessage());
		if (result.getMessage() == null) {
			result.setMessage(t.getClass().toString());
		}
		
		try {
			response.setContentType("text/plain;charset=utf-8");
			response.getWriter().write(JsonUtils.beanToJson(result));			
		} catch (Throwable tt) {			
			throw ExceptionUtils.doUnChecked(tt);
		} finally {
			errorLogger.error("mtr异常", t);
		}
	}	
}
